package top.anonyeast.interceptor;

import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 跨域拦截器
 */
public class CorsInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //表示接受任意域名的请求,也可以指定域名
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        //该字段可选，是个布尔值，表示是否可以携带cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //允许跨域的请求方法
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
        //请求头信息
        response.setHeader("Access-Control-Allow-Headers", "*");
        System.out.println(new Date() + " 前端"+ request.getMethod() +"请求:" + request.getRequestURL());
        //直接放行OPTIONS请求
        if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            response.setStatus(response.SC_OK);
            return true;
        }
        return true;
    }
}
